package com.wosiliujing.learning.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.wosiliujing.learning.admin.dto.UserInfo;
import com.wosiliujing.learning.admin.po.SysUser;
import com.wosiliujing.learning.constant.CommonConstants;
import com.wosiliujing.learning.constant.SecurityConstants;
import com.wosiliujing.learning.entity.MyUser;
import com.wosiliujing.learning.util.R;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author liujing
 */
@Component
@AllArgsConstructor
public class MyUserDetailServiceImpl implements UserDetailsService {

    private final RemoteSysUserService remoteUserService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        R<UserInfo> result = remoteUserService.info(s,SecurityConstants.FROM_IN);
        if(ObjectUtil.isEmpty(result)||ObjectUtil.isEmpty(result.getData())){
            throw new InvalidGrantException("用户名或密码不正确");
        }
        UserInfo userInfo = result.getData();
        SysUser sysUser = userInfo.getSysUser();
        Set<String> authSet = new HashSet<>();
        authSet.addAll(Arrays.asList(userInfo.getPermission()));
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));
        MyUser user = new MyUser(sysUser.getUserId(),sysUser.getUserName(),SecurityConstants.PASSWORD_ENCODER_TYPE +sysUser.getPassword(),
                StrUtil.equals(sysUser.getLockFlag(),CommonConstants.NORMAL_LOCK_STATUS),true,true,true,authorities);
        return user;
    }
}
